<?php
declare (strict_types=1);

namespace app\middleware;

use app\exception\AuthException;
use app\exception\BaseException;
use think\facade\Cache;

class AuthMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @throws AuthException
     * @throws BaseException
     */
    public function handle(\think\Request $request, \Closure $next)
    {
        if ($request->baseUrl() != '/account/login' && !$request->isGet()) {
            $admin = $request->admin;

            if ($admin['uid'] == 1) {
                return $next($request);
            }

            $path = strtolower($request->baseUrl());
            $allowPath = Cache::get('auth_' . $admin['seller_id'] . '_' . $admin['uid'], []);

            $allowPath = array_merge($allowPath, config('rbac.skip_auth'));

            if (!isset($allowPath[$path])) {
                throw new AuthException();
            }
        }
        return $next($request);
    }
}
